package es.titoapps.spanishhandball.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import es.titoapps.spanishhandball.configuration.Globals;
import es.titoapps.spanishhandball.entities.New;
import es.titoapps.spanishhandball.entities.TeamClassification;
import es.titoapps.spanishhandball.rssreader.HTMLParser;

import android.content.Context;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class NetworkTools {

	
	
	public static void downloadImage(New currentNew,String imageUrl){
		
		DefaultHttpClient mHttpClient = new DefaultHttpClient();
		HttpGet mHttpGet = new HttpGet(URI.create(imageUrl));
		HttpResponse mHttpResponse;
		try {
			mHttpResponse = mHttpClient.execute(mHttpGet);
			
			if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				  	HttpEntity entity = mHttpResponse.getEntity();
				    if ( entity != null) {
				      // insert to database
				    	byte[]arrayImagen=EntityUtils.toByteArray(entity);
				    	currentNew.setImage(arrayImagen);
				    }
				}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
//	private final String PATH = "/data/data/com.helloandroid.imagedownloader/";  //put the downloaded file here
//    
//	 
//    public void DownloadFromUrl(String imageURL, String fileName) {  //this is the downloader method
//            try {
//                    URL url = new URL("http://yoursite.com/&quot; + imageURL); //you can write here any link
//                    File file = new File(fileName);
//
//                    long startTime = System.currentTimeMillis();
//                    Log.d("ImageManager", "download begining");
//                    Log.d("ImageManager", "download url:" + url);
//                    Log.d("ImageManager", "downloaded file name:" + fileName);
//                    /* Open a connection to that URL. */
//                    URLConnection ucon = url.openConnection();
//
//                    /*
//                     * Define InputStreams to read from the URLConnection.
//                     */
//                    InputStream is = ucon.getInputStream();
//                    BufferedInputStream bis = new BufferedInputStream(is);
//
//                    /*
//                     * Read bytes to the Buffer until there is nothing more to read(-1).
//                     */
//                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
//                    int current = 0;
//                    while ((current = bis.read()) != -1) {
//                            baf.append((byte) current);
//                    }
//
//                    /* Convert the Bytes read to a String. */
//                    FileOutputStream fos = new FileOutputStream(file);
//                    fos.write(baf.toByteArray());
//                    fos.close();
//                    Log.d("ImageManager", "download ready in"
//                                    + ((System.currentTimeMillis() - startTime) / 1000)
//                                    + " sec");
//
//            } catch (IOException e) {
//                    Log.d("ImageManager", "Error: " + e);
//            }
//
//    }
	
	
	public static String getHtml(String url,String codificacion) throws ClientProtocolException, IOException
	{
	    HttpClient httpClient = new DefaultHttpClient();
	    HttpContext localContext = new BasicHttpContext();
	    HttpGet httpGet = new HttpGet(url);
	    HttpResponse response = httpClient.execute(httpGet, localContext);
	    StringBuffer result =new StringBuffer();
	    
	    BufferedReader reader = new BufferedReader(
	        new InputStreamReader(response.getEntity().getContent(), codificacion)
	      );
	    
//	    BufferedReader reader = new BufferedReader(
//	        new InputStreamReader(
//	          response.getEntity().getContent()
//	        )
//	      );

	    String line = null; 
	    while ((line = reader.readLine()) != null){
	    	
	    	result.append(line);
	    }
	    
	    
	    
//	    byte[] bytes=nuevo.getBytes();
//	    nuevo=new String(bytes, "ISO-8859-1");
//	    String otronuevo=new String(bytes, "UTF-8");
	    return result.toString();	
//	    return result.toString();
	}
	
	public static String loadHTMLData(New currentNew){
		
		try {
			
			String htmlData = NetworkTools.getHtml(currentNew.getLink(),Utilities.getCodificacion(currentNew.getSource()));

			if(!htmlData.equalsIgnoreCase("")){
				Document doc = Jsoup.parse(htmlData);

				String bodyClass="";

				if(currentNew.getSource().equalsIgnoreCase("MARCA"))
					bodyClass="cuerpo_articulo";
				else if(currentNew.getSource().equalsIgnoreCase("MUNDODEPORTIVO"))
					bodyClass="txtnoti";
				else if(currentNew.getSource().equalsIgnoreCase("SPORT"))
					bodyClass="cuerponoticia";
				else if(currentNew.getSource().equalsIgnoreCase("MUNDOBALONMANO"))
					bodyClass="entry";
				else if (currentNew.getSource().equalsIgnoreCase("AS"))
					return HTMLParser.parseASHTML(doc,currentNew);
				else if(currentNew.getSource().equalsIgnoreCase("ALAMADERA"))	
					bodyClass="entry-body";
				else if(currentNew.getSource().equalsIgnoreCase("DEROSCA"))	
					return HTMLParser.parseDeRoscaHTML(doc);
				else if(currentNew.getSource().equalsIgnoreCase("MUCHOBALONMANONOTICIAS")
						||currentNew.getSource().equalsIgnoreCase("MUCHOBALONMANOACTUALIDAD"))
					return HTMLParser.parseMuchoBMHTML(doc,currentNew);

				return HTMLParser.parseGenericHTMLNew(doc,bodyClass,currentNew);
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	
	public static ArrayList<TeamClassification> getClasificationHtml() throws ClientProtocolException, IOException
	{
	   String htmlData=NetworkTools.getHtml(Globals.getUrlClasificacionAsobal(),"UTF-8");
	   ArrayList<TeamClassification> clasificacion=null;
	   
	   if(!htmlData.equalsIgnoreCase("")){
			Document doc = Jsoup.parse(htmlData);

			String bodyClass="clasificacion";

			clasificacion= HTMLParser.parseClasification(doc,bodyClass);
			
		}
	   
	   return clasificacion;
	}
	
	public static boolean internetAvailable(Context context) {
		
		ConnectivityManager conMgr =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo i = conMgr.getActiveNetworkInfo();
		if (i == null)
			return false;
		if (!i.isConnected())
			return false;
		if (!i.isAvailable())
			return false;

		return true;

	}


}
